package com.woniu.account.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.account.dao.TGymAccountMapper;
import com.woniu.account.dto.*;
import com.woniu.account.form.BindingForm;
import com.woniu.account.model.TGymAccount;
import com.woniu.account.model.TLoginLog;
import com.woniu.account.service.TGymAccountService;
import com.woniu.account.service.TLoginLogService;
import com.woniu.core.exception.account.AccountException;
import com.woniu.core.exception.account.AccountExceptionCode;
import com.woniu.core.util.JwtUtil;
import com.woniu.core.util.Result;
import com.woniu.core.util.WebUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "QQ登录接入接口")
public class QQLoginController {

    private RestTemplate restTemplate = new RestTemplate();

    @Autowired
    private StringRedisTemplate srt;

    @Autowired
    private TLoginLogService lls;

    @Autowired
    private TGymAccountService gymAccountService;
    @Resource
    private TGymAccountMapper tGymAccountMapper;

    /**
     * 绑定qq
     *
     * @param form
     * @return
     */
    @ApiOperation("qq绑定")
    @PostMapping("/binding.gym")
    public Result<String> binding(@RequestBody BindingForm form) {
        //获取gymId
        Integer gymId = JwtUtil.getUserId(4);
        if (gymId == null) throw new AccountException(AccountExceptionCode.THIS_GYM_NOT_FIND);
        TGymAccount gymAccount = gymAccountService.getById(gymId);
        if (gymAccount == null) throw new AccountException(AccountExceptionCode.THIS_GYM_NOT_FIND);
        gymAccount.setQqOpenid(form.getOpenId());
        gymAccount.setFigureurl(form.getFigureurl_qq_1());
        gymAccount.setNickName(form.getNickname());
        gymAccount.setGender(form.getGender());
        gymAccountService.updateById(gymAccount);
        return Result.getResult(String.class).setMsg("绑定成功");
    }

    /**
     * 解绑qq
     *
     * @return
     */
    @ApiOperation("解绑qq")
    @GetMapping("/outBinding.gym")
    public Result<String> outBinding() {
        //获取gymId
        Integer gymId = JwtUtil.getUserId(4);
        if (gymId == null) throw new AccountException(AccountExceptionCode.THIS_GYM_NOT_FIND);
        TGymAccount gymAccount = gymAccountService.getById(gymId);
        if (gymAccount == null) throw new AccountException(AccountExceptionCode.THIS_GYM_NOT_FIND);
        gymAccount.setQqOpenid(null);
        gymAccount.setFigureurl("");
        gymAccount.setNickName("");
        gymAccount.setGender("");
        gymAccountService.updateById(gymAccount);
        return Result.getResult(String.class).setMsg("解绑成功");
    }

    @GetMapping("/qqlogin")
    @ApiOperation("QQ登录接入")
    public QqUserInfoDto qqLogin(String code)throws Throwable{
    System.out.println("111111");
    //1.获取临时令牌+访问令牌：一起了
    String url="https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=101780702&client_secret=be3cf79b89eafe3f0b8f90462aed8065&code="+code+"&redirect_uri=http://www.pawntest.com/qqlogin&need_openid=1&fmt=json";
    String value = restTemplate.getForObject(url, String.class);

    //因为临时令牌的参数中含有下划线_：所以需要转一下，不然会报格式转化错误
    //json转对象：JSONUtil.toBean   对象转json：JSONUtil.parse().toString
    QqtokenDto qtd = JSONUtil.toBean(value, QqtokenDto.class);
    System.out.println("QqtokenDto");
    System.out.println(qtd);
    //2.颁发访问令牌
    url="https://graph.qq.com/user/get_user_info?access_token="+qtd.getAccess_token()+"&oauth_consumer_key=101780702&openid="+qtd.getOpenid();
    //3.将拿到的用户信息的string字符串转成dto
    value = restTemplate.getForObject(url, String.class);
    QqUserInfoDto quid = JSONUtil.toBean(value, QqUserInfoDto.class);
    System.out.println("QqUserInfoDto");
    System.out.println(quid);
    //通过openid查询数据库
    TGymAccount gymAccount = gymAccountService.getOne(new QueryWrapper<TGymAccount>().eq("qq_openid", qtd.getOpenid()));

    if(gymAccount!=null){
        //证明存在拿到用户信息，去获取token，写接下来的业务
        HashMap<String, Object> map = new HashMap<>();
        map.put("gymId",gymAccount.getGymId());

        String token= JwtUtil.createToken(map,15*60,4);
        //将响应的结果写到前端页面
        WebUtil.getResponse().setCharacterEncoding("utf8");
        WebUtil.getResponse().setContentType("text/html;charset=utf8");
        WebUtil.getResponse().getWriter().write("<html>");
        WebUtil.getResponse().getWriter().write("<head></head>");
        WebUtil.getResponse().getWriter().write("<body>");
        WebUtil.getResponse().getWriter().write("<h1>登录成功</h1>");
        //通过子父组件传值：把小窗口的token传到大窗口，大窗口在前端调用api接收
        WebUtil.getResponse().getWriter().write("<script>window.opener.postMessage('"+token+"')</script>");
        WebUtil.getResponse().getWriter().write("</body>");
        WebUtil.getResponse().getWriter().write("</html>");
        //必须要刷新，不然数据不会显示
        WebUtil.getResponse().getWriter().flush();
    }else {
        //去注册
        TGymAccount tGymAccount = new TGymAccount();
        tGymAccount.setNickName(quid.getNickname());
        tGymAccount.setQqOpenid(qtd.getOpenid());
        tGymAccount.setGender(quid.getGender());
        tGymAccount.setFigureurl(quid.getFigureurl());

        tGymAccountMapper.insert(tGymAccount);
    }
    return quid;
}

}